package com.example.demo02.exception;

import com.example.demo02.common.ResponseEntity;
import com.example.demo02.constants.Constants;
import com.example.demo02.enums.ExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.Replace;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public <T> ResponseEntity<T> handleException(Exception e) {
        //数据有序性处理异常
        for (ExceptionEnum matchExceptionEnum : ExceptionEnum.values()) {
            if (e.getClass().isAssignableFrom(matchExceptionEnum.getRootCause())) {
                //匹配上了
                printStackTrace(e,matchExceptionEnum.isNeedPrintStackTraceOperate());
                ResponseEntity<T> response = ResponseEntity.error(matchExceptionEnum.getFunction().apply(e));
                response.setResult(matchExceptionEnum.getResult());
                return response;
            }
        }
        //没匹配到，默认打印堆栈错误信息
        printStackTrace(e);
        return ResponseEntity.error(Constants.DEFAULT_ERROR_MESSAGE);
    }

    private void printStackTrace(Exception e,boolean isNeedPrintStackTraceOperate){
        if(isNeedPrintStackTraceOperate){
            e.printStackTrace();
        }
    }
    private void printStackTrace(Exception e){
        printStackTrace(e,true);
    }
}
